package com.rem.concurrency.multithreading.state;

import lombok.SneakyThrows;

import java.util.concurrent.atomic.AtomicReference;

/**
 * 观察线程状态
 *
 * @author Rem
 * @date 2021-03-04
 */

public class ThreadState implements Runnable {


    @SneakyThrows
    public static void main(String[] args) {
        ThreadState threadState = new ThreadState();

        Thread thread = new Thread(threadState, "test");
        AtomicReference<Thread.State> state = new AtomicReference<>(thread.getState());
        System.err.println("初始1：" + state);

        thread.start();
        state.set(thread.getState());
        System.err.println("运行2：" + state);

        //只要线程不终止就输出它的状态
        while (state.get() != Thread.State.TERMINATED) {
            Thread.sleep(100);
            //更新状态


            state.set(thread.getState());
            System.err.println("就绪 最后结束4：" + state);
        }


    }


    @SneakyThrows
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            Thread.sleep(100);
            System.out.println(Thread.currentThread().getName());
        }

    }
}
